/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.starlink.common.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author zhanghong
 * @version RedisService.java, v 0.1 2022/3/20 22:51 下午 RedisService Exp $$
 */
@Component
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean set(final String key, String value) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean set(final String key, String value, Long minutes) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value, minutes, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean setExpiredForDay(final String key, String value, Integer day) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value, day, TimeUnit.DAYS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getKey(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public <T> T getKey(String key, Class<T> clazz) {
        ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
        String value = stringStringValueOperations.get(key);
        if (value == null) {
            return null;
        }
        return JSON.parseObject(value, clazz);
    }

    public boolean del(String key) {
        redisTemplate.delete(key);
        return true;
    }

    /**
     * 清理所有的待接单redis数据
     * @param key
     * @return
     */
    public boolean clearEngineerNotify(final String key) {
        try {
            Set<String> keys = redisTemplate.keys(key + "*");
            redisTemplate.delete(keys);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
